<template>
  <div>
    <span class="follow-label fl">{{$t("webchat.relationCall")}}:</span>
    <div class="wrap">
      <ul>
        <li class="follow-agent follow-common1" v-for="item in relatedCallSheet" :key="item" @click.stop="relationCallDetail(item)">
          <p class="item">{{item}} </p>
          <i class="el-icon-close" @click.stop="closeRelatedCall(item)" v-show="masterSelect"></i>
        </li>
      </ul>
      <el-popover placement="top" width="300" ref="relationPopover" v-model="relatePopoverShow" trigger="click" @show="popoverShow">
        <div class="relationWrap" style="text-align: right; margin: 0">
          <el-input
            :placeholder="$t('business.businessTip6')"
            v-model="searchContent"
            size="mini"
            @keyup.native.enter="handleIconClick"
          >
            <i
              class="el-input__icon el-icon-search"
              slot="suffix"
              @click="handleIconClick"
            >
            </i>
          </el-input>
          <ul style="margin: 10px 0">
            <li
              v-for="(item, idx) in relatedCallListNew"
              :key="idx"
              class="relationLi font12"
              :class="{ active: isActive }"
              @click="relationChange(item)"
            >
                <div class="phon">
                    <i class="iconfont" :class="(item.CONNECT_TYPE==='dialout'||item.CONNECT_TYPE==='dialTransfer')?'icon-waihu':'icon-huru'"></i>
                    <div class="call">
                        <span class="icon-group" :class="'icon-text-right'">
                        </span>
                        <div class="top">
                            <div class="cust-name-wrap cdr-call-name" :title="item.CUSTOMER_NAME || $t('public.unknownCustomer')">
                                <span class="cust-name ellipsis">
                                {{item.CUSTOMER_NAME || $t('public.unknownCustomer')}}
                                <i :class="item.unRead?'callIsRead':''"></i>
                                </span>
                                <i class="icon iconfont icon-biaoji1 key-tag" :title="$t('call.sign')" v-show="item.KEY_TAG && isSameCallID(item.CALL_SHEET_ID)"></i>
                                <span class="time" :class="'time2'">{{item.callTime}}</span>
                            </div>
                        </div>
                        <div class="middle clearfix">
                            <div class="middleLeft">
                                <b class="cust-phone ellipsis" :title="item.checkHideNum"><span>{{item.checkHideNum}}</span></b>
                                <el-tooltip class="item" :content="callText(item)" :placement="'bottom-start'">
                                <b><span v-show="item.PROVINCE && item.PROVINCE==item.DISTRICT && !isHidenArea">({{item.PROVINCE}})</span><span v-show="item.PROVINCE && item.PROVINCE!=item.DISTRICT && !isHidenArea" class="city pro-city ellipsis" :title="item.PROVINCE+'-'+item.DISTRICT">({{item.PROVINCE}}-{{item.DISTRICT}})</span><span v-show="item.CUSTOMER_MEMO && isShowCallMemo">({{item.CUSTOMER_MEMO}})</span></b>
                                </el-tooltip>
                                <i v-show="item.REPEAT_CALL" class="iconfont hour-box" :class="item.REPEAT_CALL==='48h'?'icon-H':'icon-H1'"></i>
                            </div>
                             <b :class="item.STATUS" class="sta fr ellipsis">{{item.statusName}}</b>
                            <!-- <span v-if="tabType==='cdr_call' && (item.ivrkey || item.TANPING)" class="ivrKey-wrap" :class="item.CUSTOMVAR?'custom_ivrkey':''">
                                <ivr-key-detail :ivrkey="item.ivrkey" :tanping="item.TANPING" :keyMemoMap="keyMemoMap"></ivr-key-detail>
                            </span> -->
                        </div>
                        <div class="bottom clearfix">
                            <span class="call-time-len"> {{item.callTimeLen}}</span>
                            <span class="play fr" v-show="item.CALL_TIME_LENGTH && isListent" @click.stop="showListentWindow(item.FILE_SERVER, item.RECORD_FILE_NAME, item.STATUS, item.PBX, item.CALL_TIME_LENGTH)"><strong></strong></span>
                            <span v-if="item.SERVICENUMALIAS" class="fl callend-num ellipsis">{{item.SERVICENUMALIAS}}</span>
                            <span v-else class='fl ellipsis callend-num' :title="(item.CONNECT_TYPE==='dialout'||item.CONNECT_TYPE==='dialTransfer')?item.CALL_NO:item.CALLED_NO">{{(item.CONNECT_TYPE==='dialout'||item.CONNECT_TYPE==='dialTransfer')?item.CALL_NO:item.CALLED_NO}}</span>
                        </div>
                        <div class="bottom1 clearfix">
                            <span class="middle4-con ellipsis">
                                <span class="server-name">{{item.SERVICENUMALIAS?item.SERVICENUMALIAS:item.CALLED_NO}}</span>
                                <i class="icon iconfont icon-dailingqu" v-show="item.QUEUE_NAME"></i>
                                <span v-show="item.QUEUE_NAME" :title="$t('public.queues')">{{item.QUEUE_NAME}}</span>
                            </span>
                            <span v-if='item.CUSTOMER_STATUS' v-statusColor="item.CUSTOMER_STATUS" class="cust-type ellipsis fr">
                            {{item.customerStatus}}
                            </span>
                        </div>
                    </div>
                </div>
                 <div v-show="isActive" class="relationDuihao">
                    <i class="el-icon-check" style="color: #fff"></i>
                </div>
            </li>
          </ul>
          <el-button
            type="primary"
            size="mini"
            style="margin-top: 10px"
            @click="saveRelatedCall"
            >{{ $t("public.save") }}</el-button
          >
        </div>
      </el-popover>
      <div class="follow-agent-wrap">
        <span
          class="follow-agent-add follow-common"
          v-popover:relationPopover
          @click="addRelationCall"
          v-if="masterSelect"
          ><i class="el-icon-plus"></i> {{ $t("public.add") }}</span
        >
      </div>
    </div>
    <el-dialog
      :visible.sync="relatedCallIsShow"
      width="1000px"
      :title="$t('intelligentQualityCheck.intelCallRecord')"
      append-to-body
      @close="offAudio" @open="openAudio"
    >
      <div class="detailWrap">
        <detail-table :callData="callData" :audioId="audioId" :pauseAudio="pauseAudio"></detail-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {timeFormat, getCallTimeLength, getCache, checkHideTel, isHasFunc, m7Language, getCacheByKey} from '@/utils/m7Utils.js'
import DetailTable from '@/components/public-modules/cust-tab-content/call-detail/DetailTable.vue'
export default {
    name:'relatedCall',
    props:{ 
      relatedCallSheet: {
        type: Array,
        default:() => []
      },//已关联会话
      relatedCallShow: {type: Boolean, default: true},//详情中不能再点击详情
      masterSelect:{type:Boolean, default: true},//是否有权限操作关联会话
    },
    data(){
        return{
          relatedCallIsShow:false,//会话详情弹窗
          isActive:false,//动态class
          searchContent:'',//搜索会话input框
          relatedCallList:[],//会话搜索数据
          showHistory:true,//会话历史详情是否展示
          busId:'',//会话id
          relatePopoverShow: false,
          hasTransAuth: false,
          isHidenArea: false,
          isListent: false,
          callData:{},
          audioId: 'business_info_audio' + Math.random().toFixed(4),
          pauseAudio: 'open',
        }
    },
    components:{
      DetailTable
    },
    computed: {
      relatedCallListNew () {
        let list = this.relatedCallList || []
        for (let i = 0; i < list.length; i++) {
        //   if (this.tabType === 'cdr_call' || this.tabType === 'cdr_outbound') { // 来电匹配服务号名称
        const phoneNumber = list[i].CALL_NO
        if (phoneNumber) {
            let serverNoList = this.serviceNoList || []
            for (let m = 0; m < serverNoList.length; m++) {
            if (serverNoList[m].Exten === phoneNumber && serverNoList[m].DisplayName) {
                list[i].SERVICENUMALIAS = serverNoList[m].DisplayName
                break
            }
            }
        }
         list[i].CUSTOMER_ID = '00000000000000000000'
          let agentObj = ''
          if (this.$store.getters.agents) {
            agentObj = this.$store.getters.agents[list[i].DISPOSAL_AGENT] || ''
          }
          if (agentObj) {
            list[i].agentName = agentObj.displayName || ''
          } else {
            list[i].agentName = ''
          }
          if (this.isEnglis === 'en' && (list[i].CUSTOMER_ID === '00000000000000000000' || !list[i].CUSTOMER_ID)) {
            if (list[i].CUSTOMER_NAME === '多个匹配客户') {
              list[i].CUSTOMER_NAME = this.$t('customer.customerSlot.unlocation')
            } else if (list[i].CUSTOMER_NAME === '未知客户') {
              list[i].CUSTOMER_NAME = this.$t('public.unknownCustomer')
            }
          }
          list[i].statusName = this.getResultNameById(list[i].STATUS, 'status') // 处理通话状态名称
          list[i].queueName = this.getResultNameById(list[i].ERROR_MEMO, 'queues') // 处理技能组名称
          list[i].customerStatus = this.getStatusName(list[i].CUSTOMER_STATUS) // 客户状态
          list[i].callTime = timeFormat(list[i].OFFERING_TIME, 'card') // 通话时间
          list[i].callTimeLen = getCallTimeLength(list[i].CALL_TIME_LENGTH) // 通话时长
          list[i].checkHideNum = (list[i].CONNECT_TYPE === 'dialout' || list[i].CONNECT_TYPE === 'dialTransfer') ? checkHideTel(list[i].CALLED_NO, this.$store.state.session.user) : checkHideTel(list[i].CALL_NO, this.$store.state.session.user) // 隐藏号码
        }
        return list
      },
    },
    directives: { // 自定义指令 改变文字color的值
      statusColor: {
        inserted (el, binding, vnode) {
          let self = vnode.context
          let statusConfig = {}
          let custTmpls = self.$getCache('custTmpls')
          if (custTmpls && custTmpls[0]) { // 以防报错
            statusConfig = custTmpls[0].statusConfig || {}
          }
          if (binding.value) {
            if (statusConfig && statusConfig[binding.value]) {
              el.style.color = statusConfig[binding.value].color
            } else {
              el.style.color = self.statusColors[binding.value] ? self.statusColors[binding.value] : '#009FE3'
            }
          }
        },
        update (el, binding, vnode) {
          let self = vnode.context
          let statusConfig = {}
          let custTmpls = self.$getCache('custTmpls')
          if (custTmpls && custTmpls[0]) { // 以防报错
            statusConfig = custTmpls[0].statusConfig || {}
          }
          if (binding.value) {
            if (statusConfig && statusConfig[binding.value]) {
              el.style.color = statusConfig[binding.value].color
            } else {
              el.style.color = self.statusColors[binding.value] ? self.statusColors[binding.value] : '#009FE3'
            }
          }
        }
      }

    },
    methods:{  
      callTimeLen (time) {
        return getCallTimeLength(time)
      },
        //添加关联通话
      addRelationCall(){
      },
      popoverShow(){
        this.relatePopoverShow = true
      },
      //保存关联通话
      saveRelatedCall(){
        if(this.isActive&&this.searchContent){
          this.$emit('saveRelatedCall',this.searchContent)
          this.searchContent = ''
          this.relatedCallList = []
          this.relatePopoverShow = false
        }else{
          this.$message.error(this.$t('business.selectCall'))
        }
      },
      //通话列表点击更改class
      relationChange(){
        this.isActive = !this.isActive
      },
      //关联通话详情
      relationCallDetail(number){
        if(this.relatedCallShow){
            this.$store.dispatch('relocationCustomerAtTable', {_id: number, self: this}).then((resp) => {
              if (resp) {
                this.callData  = resp
              } else {
                this.callData  = []
              }
              //当详情为空时不打开弹窗
              if(this.callData && Object.keys(this.callData).length >0){
                  this.relatedCallIsShow = true
              }
            })
        }
      },
      //关闭弹窗
      detailClose(){
        this.relatedCallIsShow = false
      },
      offAudio () {
        this.pauseAudio = 'close'
        let myAudio = document.getElementById('quality-autoplay_' + this.audioId + '_old')
        if (myAudio) {
          if (myAudio.currentSrc) {
            myAudio.pause()
          }
        }
      },
      openAudio () {
        this.pauseAudio = 'open'
      },
      //删除关联通话
      closeRelatedCall(number){
        this.$emit('closeRelatedCall',number)
      },
      //搜索
      handleIconClick(){
        this.isActive = false
        if(!this.searchContent){
          this.relatedCallList = []
        }else{
            let data = {
                CALL_SHEET_ID: this.searchContent,
                autoqc: true
            }
            this.$store.dispatch('queryCallList', data).then((res) => {
                if (res && res.list && res.list.length) {
                  this.relatedCallList = res.list
                } else {
                  this.$message.error(this.$t('call.callTip'))
                  this.relatedCallList = []
                }
            })
        }
      },
      getInvestigate (INVESTIGATE, CHILD_INVESTIGATE) {
//        let options = this.$store.state.session.dicMap.investigate
        let options = this.$getCache('investigate')
        let name = ''
        let childName = ''
        console.log(options)
        for (let i = 0; i < options.length; i++) {
          if (INVESTIGATE === options[i].value) {
            name = options[i].name
            console.log(options[i])
            console.log('CHILD_INVESTIGATECHILD_INVESTIGATE')
            if (options[i].children && options[i].children.length > 0 && CHILD_INVESTIGATE) {
              for (let k = 0; k < options[i].children.length; k++) {
                if (CHILD_INVESTIGATE === options[i].children[k].value) {
                  childName = options[i].children[k].name
                  break
                }
              }
            }
            break
          }
        }
        if (!name) {
          name = INVESTIGATE || '' // 若字典配置被删除就默认显示数字eg:1
        }
        if (!childName) {
          childName = CHILD_INVESTIGATE || ''
        } else {
          childName = '--' + childName
        }
        return name + childName
      },
      callText (item) {
        let province = ''
        let distrist = ''
        let custom_mome = ''
        if (item.PROVINCE && item.PROVINCE==item.DISTRICT && !this.isHidenArea) {
          province = '(' + item.PROVINCE + ')'
        }
        if (item.PROVINCE && item.PROVINCE!=item.DISTRICT && !this.isHidenArea) {
          distrist = '(' + item.PROVINCE + '-' + item.DISTRICT + ')'
        }
        if (item.CUSTOMER_MEMO && this.isShowCallMemo) {
          custom_mome = '(' + item.CUSTOMER_MEMO + ')'
        }
        return province + distrist + custom_mome
      },
      showListentWindow (server, name, status, pbx, callTimeLen) { // 录音弹窗
        this.callStatus = status || ''
        if (server.indexOf('record.7moor.com') > -1 || server.indexOf('m7-record.oss-cn-hangzhou') > -1 || server.indexOf('aliyuncs.com') > -1) {
          server = 'https' + server.substr(server.indexOf(':'), server.length)
          if (status === 'voicemail' || status === 'dealing') { // 只有已接听和已留言才会是有效的录音地址
            this.fileServer = server
            this.fileName = name
            this.callTimeLen = callTimeLen
          }
          this.listent = true
        } else if (document.location.protocol === 'https:') {
          let self = this
          if (pbx) {
            getCache('accountPbx', pbx, this, function (pbxObj) {
              if (pbxObj) {
                if (pbxObj.assDomain) {
                  let assDomain = pbxObj.assDomain
                  if (assDomain.substr(assDomain.length - 1, assDomain.length) === '/') {
                    assDomain = assDomain.substr(0, assDomain.length - 1)
                  }
                  server = assDomain
                }
              }
              if (status === 'voicemail' || status === 'dealing') { // 只有已接听和已留言才会是有效的录音地址
                self.fileServer = server
                self.fileName = name
                self.callTimeLen = callTimeLen
              }
              self.listent = true
            })
          } else {
            if (status === 'voicemail' || status === 'dealing') { // 只有已接听和已留言才会是有效的录音地址
              this.fileServer = server
              this.fileName = name
              this.callTimeLen = callTimeLen
            }
            this.listent = true
          }
        } else {
          if (status === 'voicemail' || status === 'dealing') { // 只有已接听和已留言才会是有效的录音地址
            this.fileServer = server
            this.fileName = name
            this.callTimeLen = callTimeLen
          }
          this.listent = true
        }
        this.refreshAudio = Math.random()
      },
      getResultNameById (master, type) { // 根据id取name （status && queues）
        let current = ''
        let list = []
        if (type === 'status') {
          list = this.$getCache('callStatus') || []
        } else if (type === 'queues') {
          list = this.$getCache('queues') || []
        }
        if (!list) {
          return ''
        }
        for (let i in list) {
          if (type === 'status') {
            if (list[i].code_value === master) {
              current = m7Language('globalChineseKey.' + list[i].code_name, null, true) || list[i].code_name || ''
              break
            }
          } else if (type === 'queues') {
            if (list[i].Exten === master) {
              current = list[i].DisplayName || ''
              break
            }
          }
        }
        return current
      },
      getStatusName (status) {
        let cs = ''
        let custTmpls = this.$getCache('custTmpls')[0]
        if (custTmpls && custTmpls.status) {
          cs = custTmpls.status[status]
        }
        return cs
      },
    },
    beforeMount(){
      this.$store.dispatch('getCache', {type: 'translationConfig'}).then((res) => {
        if (res.sumAgent) {
        let userId = this.$store.state.session.user._id
        if (res.uids && res.uids.indexOf(userId) > -1) {
            this.hasTransAuth = true
        }
        }
      })
      let callValue = '' // this.item.STATUS
      this.$store.dispatch('getDicCacheName', {type: 'callStatus', value: callValue}).then((req) => { // 获取通话状态
        this.cardLoading = false
        if (this.$store.state.session.user.isAdmin || !isHasFunc('func_user_call_sheet_listen_file', this.$store.state.session.user)) {
          this.isListent = true
        }
      })
    },
    mounted(){
    }
};
</script>

<style lang='stylus' scoped>
    @import '../../../../assets/common.styl'
    .follow-label
      line-height 24px
      font-size 12px
    .follow-agent
      .item
        width 88px
        line-height 24px
        text-overflow ellipsis
        overflow hidden
        white-space nowrap
    .follow-agent-wrap
      padding-left 72px
      .follow-common
        float left
        position relative
        line-height 24px
        margin 0 0 10px 10px
        padding 0 10px
        border-radius 4px
        font-size 12px
      .follow-agent-add
        border 1px solid $c-main
        color $c-main
        cursor pointer
      .follow-agent
        line-height 26px
        background-color $c-bus-label
        color #fff
        &:hover
          .el-icon-close
            display block
        .el-icon-close
          display none
          position absolute
          right -10px
          top -10px
          width 24px
          height 24px
          font-size 16px
          line-height 24px
          transform scale(0.6)
          text-align center
          color #fff
          background-color $c-pink
          border-radius 50%
          border 1px solid #fff
          cursor pointer
    .detail-table-wrap
      position fixed
      top 0
      left 0
      right 0
      bottom 0
      background rgba(0,0,0,.5)
      z-index 200
    .approval
      padding-top 20px
    .text 
      color #000
      cursor pointer
      font-size 12px
.relationWrap
  .active 
    position relative
    padding 8px
    border 2px solid #459AE9
  .relationLi
    position relative
    padding 8px
    .relationDuihao
      position:absolute
      height:16px
      width:16px
      top:-1px
      right:-1px
      background rgb(69, 154, 233)
    .phon
        padding 10px
        height 92px
        box-sizing border-box
        background-color $cf-white
        display flex
        cursor pointer
        align-items center
        color $cf-gray0
        position relative
        line-height 1
        .hour-box
            color $c-main
            font-size 22px
            padding 0 3px
        .icon-waihu,.icon-huru,.icon-zhuanjie3
            font-size 12px
            position absolute
            z-index 9
            line-height 18px
            left 9px
            top 52px
        .icon-waihu
            color $c-email
        .icon-huru
            color $c-cAgent
        .sta
            color $c-pink
        .dealing,.voicemail
            color $c-email
        .blackList,.limit
            color $cf-gray3
        .ivrKey-wrap
            color  $cf-gray4
            position absolute
            bottom 26px
            right 10px
        .custom_ivrkey
            bottom 52px
        .call
            width 260px
            flex 3
            padding-left 16px
            display inline-block
            .top
                height 16px
                line-height 16px
                .cust-name-wrap
                  .cust-name
                    float left
                    max-width 14em
                    font-size 14px
                    font-weight bold
                    color $cf-gray2
                    position relative
                    padding-right 10px
                    .callIsRead
                        display block
                        position absolute
                        width 8px
                        height 8px
                        background #f37474
                        border-radius 50%
                        right 0
                        top 0
                .time
                    float right
                    font-weight normal
                    color $cf-gray6
            .middle
                display flex
                justify-content space-between
                height 28px
                line-height 28px
                .middleLeft
                    text-align left
                    flex 3
                    overflow hidden
                    text-overflow ellipsis
            .bottom
                position relative
                margin-bottom 5px
                .play
                    position absolute
                    top -4px
                    right 48px
                .call-time-len
                    float right
                    width 50px
                    color $cf-gray6
                .callend-num
                    color $cf-gray4
                    max-width 19em
                    vertical-align bottom
            .bottom1
                display flex
                justify-content space-between
                height 13px
                .middle4-con
                    text-align left
                    flex 1
                    overflow hidden
                    text-overflow ellipsis
</style>
